# Copyright (C) 2006-2008 by Sergio Pistone
# sergio_pistone@yahoo.com.ar
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

require File.expand_path( File.dirname( __FILE__ ) + "/http" )

module KDE

	@@proxy_settings_file = "#{ENV["HOME"]}/.kde/share/config/kioslaverc"

	@@cfg_type_regexp = /^ *ProxyType *= *([0-4]+) *$/
	@@excluded_regexp = /^ *NoProxyFor *= *([^ ]+) *$/
	@@reverse_regexp  = /^ *ReversedException *= *([^ ]+) *$/
	@@protocol_regexp = /^ *([^: ]+):\/+/

	# returns proxy_url, excluded_urls, reverse
	def KDE.get_proxy_settings( protocol="http" )

		protocol = protocol.downcase()
		raise ArgumentError( "Invalid protocol specified" ) if ! ["http", "https", "ftp"].include?( protocol )

		proxy_regexp = /^ *#{protocol}Proxy *= *([^ ]+) *$/

		cfg_type = proxy_url = excluded_urls = reverse = ""
		begin
			File.open( @@proxy_settings_file ).each() do |row|
				row.chomp!()
				md = @@cfg_type_regexp.match( row )
				cfg_type = md[1] if md
				md = proxy_regexp.match( row )
				proxy_url = md[1] if md
				md = @@excluded_regexp.match( row )
				excluded_urls = md[1] if md
				md = @@reverse_regexp.match( row )
				reverse = md[1] if md
			end
		rescue Exception => e
			puts "Error reading KDE proxy settings file: " + e.to_s()
			return nil, [], false
		end

		# cfg_type == 0: connect directly to the internet
		# cfg_type == 1: manual configuration
		# cfg_type == 2: use proxy configuration url (can't do anything with this one)
		# cfg_type == 3: detect automatically (can't do anything with this one either)
		# cfg_type == 4: same as manual configuration but values are read from enviroment variables

		if cfg_type != "1" && cfg_type != "4"
			return nil, [], false
		elsif cfg_type == "4"
			proxy_url = ENV[proxy].to_s().strip()
			excluded_urls = ENV[excluded_urls].to_s().strip()
 		end

		return nil, [], false if proxy_url == ""

		# verify proxy_url
		proxy_url = HTTP.normalize_url( proxy_url, "http" )
		return nil, [], false if proxy_url == nil

		# parse excluded_urls list
		excluded_urls_list = []
		excluded_urls.split( "," ).each() do |url|
			url = HTTP.normalize_url( url, "http" )
			excluded_urls_list.insert( -1, url ) if url && !excluded_urls_list.include?( url )
		end

		reverse = reverse.strip().downcase() == "true"

		return proxy_url, excluded_urls_list, reverse
	end

end

